<template>
  <Dialog v-model="dialogVisible2" title="上传视频" width="1200" height="600">
    <input type="file" multiple @change="uploadChang" />
    <BaseButton type="primary" @click="startUpload">开始上传 </BaseButton>
    <ElTable :data="fileUploadList" style="width: 100%">
      <ElTableColumn prop="sort" label="序号" />
      <ElTableColumn prop="name" label="文件名称" width="300" />
      <ElTableColumn prop="size" label="大小">
        <template #default="scope">
          <span>{{ (scope.row.size / (1024 * 1024)).toFixed(2) }}M</span>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="progress" label="上传进度">
        <template #default="scope">
          <ElProgress :percentage="(scope.row.progress * 100).toFixed(2)" />
        </template>
      </ElTableColumn>
      <ElTableColumn prop="status" label="状态">
        <template #default="scope">
          <ElTag type="info" v-if="scope.row.status == 0">待上传</ElTag>
          <ElTag type="warning" v-if="scope.row.status == 1">上传</ElTag>
          <ElTag type="success" v-if="scope.row.status == 2">完成</ElTag>
          <ElTag type="danger" v-if="scope.row.status == 3">上传失败</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="active" label="操作">
        <template #default="scope">
          <ElButton
            @click="deleteFile(scope.row.id)"
            type="danger"
            :icon="useIcon({ icon: 'ri:delete-bin-2-line' })"
            circle
          />
        </template>
      </ElTableColumn>
    </ElTable>
    <template #footer>
      <BaseButton type="primary" @click="save"> 保存</BaseButton>
      <BaseButton @click="dialogVisible2 = false">返回</BaseButton>
    </template>
  </Dialog>
</template>
<script>
import OSS from 'ali-oss'
import { useUserStore } from '@/store/modules/user'
import { ref } from 'vue'
import { Dialog } from '@/components/Dialog'

import { ElTable, ElTableColumn, ElTag, ElProgress, ElButton } from 'element-plus'
import { addBatchSysVideoApi } from '@/api/resLibrary/video'
import { useIcon } from '@/hooks/web/useIcon'

const client = new OSS({
  // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
  // region: 'oss-cn-beijing',
  // // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  // accessKeyId: 'LTAI5tLGBDzFhAEQQ1GoyBgf',
  // accessKeySecret: 'wwVvSrlAGtSX2ZCFPWssShmX4WRzRt',
  // // 填写存储空间名称。
  // bucket: 'english-1234'
  //马

  // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
  region: 'oss-cn-qingdao',
  // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  accessKeyId: 'LTAI5t9oQ4VSCvy56TgSVEj9',
  accessKeySecret: 'nYKn9dZrSklj01SvRGkLAuwa77quNO',
  // 填写存储空间名称。
  bucket: 'english-12345'
})
export default {
  components: {
    Dialog,
    ElTable,
    ElTableColumn,
    ElProgress,
    ElTag,
    ElButton
  },
  props: ['currentRow'],
  setup(props) {
    const userStore = useUserStore()
    const dialogVisible2 = ref(false)
    const fileUploadList = ref([])
    const asyncNum = ref(0)
    const uploadChang = async (file) => {
      const fileList = file.target.files
      for (let i = 0; i < fileList.length; i++) {
        const vo = fileList[i]
        vo.status = 0
        vo.progress = 0
        vo.url = ''
        vo.id = i
        vo.sort = i + 1
      }
      fileUploadList.value = [...fileList]
    }
    //开始上传
    const startUpload = async () => {
      const fileList = fileUploadList.value
      for (let i = 0; i < fileList.length; i++) {
        const vo = fileList[i]
        await multipartUpload(vo)
      }
    }
    //开始上传
    const deleteFile = (id) => {
      const fileList = fileUploadList.value
      fileList.splice(id, 1)
      for (let i = 0; i < fileList.length; i++) {
        const vo = fileList[i]
        vo.id = i
        vo.sort = i + 1
      }
      fileUploadList.value = [...fileList]
    }
    const progress = (p, _checkpoint, file) => {
      const id = file.id
      const fileUploadListArr = fileUploadList.value
      const oldFile = fileUploadListArr[id]
      oldFile.status = 1
      if (p == 1) {
        oldFile.status = 2
      }
      oldFile.progress = p
      fileUploadListArr[id] = oldFile
      fileUploadList.value = [...fileUploadListArr]
      // Object的上传进度。
      // console.log(p, '上传进度', file)
      // 分片上传的断点信息。
      // console.log(_checkpoint, 'chpoit')
    }

    const headers = {
      // 指定Object标签，可同时设置多个标签。
      'x-oss-tagging': 'Tag1=1&Tag2=2',
      // 指定初始化分片上传时是否覆盖同名Object。此处设置为true，表示禁止覆盖同名Object。
      'x-oss-forbid-overwrite': 'true'
    }

    // 开始分片上传。
    async function multipartUpload(file) {
      const fileName = getUploadFileName(file.name)
      console.log(fileName, 'fileName')
      try {
        // 依次填写Object完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径（例如D:\\localpath\\examplefile.txt）。Object完整路径中不能包含Bucket名称。
        // 如果本地文件的完整路径中未指定本地路径（例如examplefile.txt），则默认从示例程序所属项目对应本地路径中上传文件。
        const result = await client.multipartUpload(fileName, file, {
          progress: (a, b) => {
            return progress(a, b, file)
          },
          headers,
          // 指定meta参数，自定义Object的元数据。通过head接口可以获取到Object的meta数据。
          meta: {
            year: 2020,
            people: 'test'
          }
        })
        console.log(result, 'result')
        const id = file.id
        const fileUploadListArr = fileUploadList.value
        const oldFile = fileUploadListArr[id]
        oldFile.url = '/' + result.name
        fileUploadListArr[id] = oldFile
        fileUploadList.value = [...fileUploadListArr]
        asyncNum.value = asyncNum.value - 1
        console.log()
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        const head = await client.head(fileName)
        console.log(head, 'head')
      } catch (e) {
        // 捕获超时异常。
        if (e.code === 'ConnectionTimeoutError') {
          console.log('TimeoutError')
          // do ConnectionTimeoutError operation
        }
        const id = file.id
        const fileUploadListArr = fileUploadList.value
        const oldFile = fileUploadListArr[id]
        oldFile.status = 3
        fileUploadListArr[id] = oldFile
        fileUploadList.value = [...fileUploadListArr]
      }
    }

    const isShowOssUploadModel = () => {
      dialogVisible2.value = true
    }
    const getUploadFileName = (fileName) => {
      const userId = userStore.getUserInfo.id
      const realName = userStore.getUserInfo.realName
      const fileNameExt = fileName.substring(fileName.length - 3)
      const fileNameMain = fileName.substring(0, fileName.length - 4)
      const fileNameDh = fileNameMain.replace(/\s{1,}|\./g, '')
      const uploadFileName =
        realName +
        '_' +
        userId +
        '/' +
        props.currentRow.code +
        '/视频/' +
        fileNameDh +
        '/' +
        fileNameDh +
        '.' +
        fileNameExt
      return uploadFileName
    }
    const save = () => {
      const aa = {}
      let fileUrlList = []
      aa.videoTypeId = props.currentRow.id
      const fileList = fileUploadList.value
      for (const fileListElement of fileList) {
        fileUrlList.push(fileListElement.url)
      }
      aa.fileUrlList = fileUrlList
      addBatchSysVideoApi(aa).then(() => {
        fileUploadList.value = []
        dialogVisible2.value = false
      })
    }
    return {
      dialogVisible2,
      uploadChang,
      isShowOssUploadModel,
      save,
      startUpload,
      deleteFile,
      fileUploadList
    }
  },
  methods: { useIcon }
}
</script>
